
/**
 * 
 * @param {*} file 
 * 图片压缩
 * @returns url
 */
export const  handleFileChange=(file)=> {
    // 创建一个 FileReader 实例用于读取文件
    return new Promise((resolve, reject) => {
      const reader = new FileReader();

      reader.onload = (event) => {
        const image = new Image();
        image.src = event.target.result;

        image.onload = () => {
          const canvas = document.createElement("canvas");
          const ctx = canvas.getContext("2d");

          const maxWidth = 1920; // 设置最大宽度
          // const maxHeight = 600; // 设置最大高度

          let width = image.width;
          let height = image.height;

          // 根据最大宽度和最大高度等比例缩放图片尺寸
          if (width > height) {
            if (width > maxWidth) {
              height *= maxWidth / width;
              width = maxWidth;
            }
          } else {
            // if (height > maxHeight) {
            //   width *= maxHeight / height;
            //   height = maxHeight;
            // }
          }

          // 将图片绘制到 canvas 上
          canvas.width = width;
          canvas.height = height;
          ctx.drawImage(image, 0, 0, width, height);

          // 将 canvas 转换为 Blob 对象
          canvas.toBlob((blob) => {
            // 在这里可以执行上传操作，将 blob 对象发送到服务器
            console.log("Compressed image:", blob);
            const blobUrl = URL.createObjectURL(blob);
            resolve(blobUrl);
            return blob;
          }, file.type);
        };
      };

      reader.readAsDataURL(file);
    });
  }